<template>
  <div class="permission">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">权限管理</span>
      </div>
      <el-table
        :data="adminList"
        border
        style="width: 100%"
        class="admin-table"
      >
        <el-table-column
          prop="adminId"
          label="管理员ID"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="nickname"
          label="姓名"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="账号"
          align="center"
        ></el-table-column>
        <!-- <el-table-column
          prop="password"
          label="密码"
          width="120"
          align="center"
        ></el-table-column> -->
        <el-table-column label="权限" prop="roleId" align="center">
          <template slot-scope="scop">
            {{ getRoleLabel(scop.row.roleId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑管理员信息"
      :visible.sync="editDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="editForm"
        :rules="rules"
        :model="editForm"
        label-width="100px"
      >
        <el-form-item label="管理员ID">
          <el-input v-model="editForm.adminId" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="editForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="editForm.roleId">
            <el-option
              v-for="role in roles"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { adminList } from "@/api/adminUserApi";
import { mapActions, mapGetters } from "vuex";

export default {
  name: "AdminPermission",
  data() {
    return {
      adminList: [],
      roles: [
        { value: 5, label: "超级管理员" },
        { value: 4, label: "区域管理员" },
        { value: 3, label: "商店管理员" },
      ],
      rules: {
        nickname: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "姓名长度在 2 到 10 个字符之间",
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "账号长度在 5 到 20 个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "密码长度在 6 到 16 个字符之间",
            trigger: "blur",
          },
          {
            min: 6,
            max: 16,
            message: "密码长度在 6 到 16 个字符之间",
            trigger: "blur",
          },
        ],
        roleId: [{ required: true, message: "请选择权限", trigger: "change" }],
      },
      loginInfo: {}, //当前登录的用户信息
      editDialogVisible: false, // 编辑对话框的显示状态
      editForm: {}, // 编辑表单的数据
    };
  },
  computed: {
    ...mapGetters({
      adminData: "admin/getAdmin",
    }),
  },
  mounted() {
    // 检查登录信息
    if (!this.checkAdminData()) return;
    // 读取状态
    this.loginInfo = this.adminData;

    const query = {
      adminId: this.loginInfo.adminId,
    };
    //进来先查询数据
    adminList(query)
      .then((res) => {
        this.adminList = res.data;
      })
      .catch((err) => {
        console.error("查询管理员列表异常", err);
        this.$message.error("网络错误或服务器异常");
      });
  },
  methods: {
    ...mapActions({
      adminEdit: "admin/SUPER_ADMIN_EDIT",
    }),
    // 检查管理员数据是否存在
    checkAdminData() {
      if (!this.adminData) {
        this.$message.error("尚未登录");
        this.$router.push({ name: "Home" });
        return false;
      }
      return true;
    },
    // 设置管理员信息
    getRoleLabel(roleId) {
      const role = this.roles.find((r) => r.value === roleId);
      return role ? role.label : "未知角色";
    },
    handlePermissionChange(row) {
      this.$message.success(
        `管理员 ${row.name} 的权限已更新为 ${row.permission}`
      );
      // 在此处可以调用接口更新后端数据
    },
    handleEdit(row) {
      this.editForm = { ...row }; // 深拷贝当前行的数据到编辑表单
      this.editDialogVisible = true; // 打开编辑对话框
    },
    handleDelete(row) {
      this.$confirm(`确定要删除管理员 ${row.name} 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.adminList = this.adminList.filter(
            (admin) => admin.id !== row.id
          );
          this.$message.success(`管理员 ${row.name} 已删除`);
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    saveEdit() {
      // 更新管理员信息
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          this.$message({
            showClose: true,
            message: "表单填写有误，请检查后再试",
            type: "error",
          });
          return;
        }
        this.editForm.manageId = this.loginInfo.adminId;
        this.adminEdit(this.editForm)
          .then((res) => {
            this.$message.success("更新成功");
            this.adminList = res.data;
            // console.log(sessionStorage.getItem("admin_user"));
          })
          .catch((err) => {
            console.error("更新失败", err);
            // this.$message.error("网络错误或服务器异常");
          })
          .finally(() => {
            this.editDialogVisible = false; // 关闭编辑对话框
          });
      });
    },
  },
};
</script>

<style scoped>
.permission {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.admin-table {
  margin-top: 20px;
}
</style>